package cn.imatu.framework.security.xss.core;

import cn.imatu.framework.security.xss.config.SecurityXssProperties;
import cn.hutool.core.util.ArrayUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shenguangyang
 */
@RequiredArgsConstructor
public class XssCleanServletInterceptor implements AsyncHandlerInterceptor {
    private final SecurityXssProperties securityXssProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 1. 非控制器请求直接跳出
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 2. 没有开启
        if (!securityXssProperties.isEnabled()) {
            return true;
        }

        // 3. 处理 XssIgnore 注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        XssCleanIgnore xssCleanIgnore = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), XssCleanIgnore.class);
        if (xssCleanIgnore == null) {
            XssHolder.setEnable();
        } else if (ArrayUtil.isNotEmpty(xssCleanIgnore.value())) {
            XssHolder.setEnable();
            XssHolder.setXssCleanIgnore(xssCleanIgnore);
        }
        return true;
    }
}
